package com.spring;

import com.spring.annotation.AutoWired;
import com.spring.annotation.Component;
import com.spring.annotation.PostConstruct;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengjy
 * @date 2025/4/7
 */
public class BeanDefinition {
    private final String beanName;
    private final Class beanClass;
    private final Constructor<?> constructor;
    private final Map<Field,String> fieldStringMap;
    private Method postConstructor;

    public BeanDefinition(Class<?> classType) {


        Component annotation = classType.getAnnotation(Component.class);
        beanName = annotation.value().isEmpty() ? classType.getSimpleName() : annotation.value();
        beanClass = classType;
        List<Field> fields = Arrays.stream(classType.getDeclaredFields()).filter(filed -> filed.isAnnotationPresent(AutoWired.class)).toList();
        Map<Field,String> fieldMap = new HashMap<>();
        for (Field field : fields) {
            String value = field.getAnnotation(AutoWired.class).value();
            fieldMap.put(field,value.isEmpty() ? field.getName() : value);
        }
        fieldStringMap = fieldMap;

        postConstructor = Arrays.stream(classType.getDeclaredMethods()).filter(method -> method.isAnnotationPresent(PostConstruct.class)).findFirst().orElse(null);
        // 获取第一个构造函数
        constructor = classType.getConstructors()[0];
    }

    public String getBeanName() {
        return beanName;
    }

    public Class getBeanClass() {
        return beanClass;
    }

    public Constructor<?> getConstructor() {
        return constructor;
    }

    public Map<Field,String> getAutoWiredFields() {
        return fieldStringMap;
    }

    public Method getPostConstructor() {
        return postConstructor;
    }
}
